/**
 * FileName: RequestUtils Author:   zeroleavebaoyang Date:     2018/8/30 13:18 Description:
 */
package com.shiro.sso.demo.utils;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

public class RequestUtils {

    public static String getSsoUrl(HttpServletRequest request) {
        StringBuffer forwardUrl = new StringBuffer();
        String redirectUrl = request.getParameter(Constant.SSO_REDIRECT_URL);
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            forwardUrl.append("redirect:");
            if (StringUtils.isNotBlank(redirectUrl)) {
                forwardUrl.append(redirectUrl + (redirectUrl.contains("?") ? "&" : "?")
                        + SsoLoginHelper.cookieName + "="
                        + subject.getSession().getId().toString());
            } else {
                forwardUrl.append("/");
            }
        } else {
            request.setAttribute(Constant.SSO_REDIRECT_URL, redirectUrl);
            forwardUrl.append("login");
        }
        return forwardUrl.toString();
    }

    public static String getOAuthSuccessUrl(HttpServletRequest request) {
        StringBuffer forwardUrl = new StringBuffer("redirect:");
        String redirectUrl = (String) request.getSession().getAttribute(Constant.SSO_REDIRECT_URL);
        if (StringUtils.isNotBlank(redirectUrl)) {
            Subject subject = SecurityUtils.getSubject();
            forwardUrl.append(redirectUrl + (redirectUrl.contains("?") ? "&" : "?")
                    + SsoLoginHelper.cookieName + "="
                    + subject.getSession().getId().toString());
        } else {
            forwardUrl.append("/");
        }
        request.getSession().removeAttribute(Constant.SSO_REDIRECT_URL);
        return forwardUrl.toString();
    }
}
